// pages/customer/detail.js
import Validate from "../../utils/validate";

const app = getApp();
import {formatDate} from "../../utils/util";

const util = require("../../utils/util");
import network from "../../utils/network";
import Toast from '@vant/weapp/toast/toast';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        active: 0,
        customer: {},
        date: '',
        industry_name: null,
        industryPopShow: false,
        addLinkDialogShow: false,
        requestUrl: app.api.followListByCustomerId,
        requestParams: {
            customer_id: null,
            page: 1,
            page_size: 5
        },
        levelShow: false,
        birthdayShow: false,
        companyShow: false,
        addPutStorageShow: false,
        groupPopShow: false,
        userSelectShow: false,
        editInfoShow: false,
        levelArr: ['总负责人', '直接负责人', '办事员'],
        actionList: [],
        contactList: [],
        putStorageList: [],
        listData: [],
        linkUser: {
            name: null,// 名称
            dept: null,// 部门
            post: null,// 职务
            phone: null,// 手机号
            level: null,//等级
            birthday: null,// 生日
            hobbies: null,// 个人喜好
            commemoration_day: null,// 家庭成员及重要纪念日
            remark: null// 备注
        },
        putStorage: {
            company_head: null,//公司抬头
            login_account: null,//登录账号
            password: null,
            link_user: null,
            phone: null,
            email: null,
            website: null,// 网站
        },
        minDate: new Date(new Date().getFullYear() - 60, 0, 1).getTime(),
        maxDate: new Date().getTime(),
        industry_arr: [],// 行业待选项
        salesFunnelArr: [],// 销售漏斗待选项
        groupArr: [],//所属集团待选项
        userArr: [],// 客户负责人待选项
        resourceArr: [], // 推荐资源待选项
        companyArr: [], // 公司待选项
        editInfo: {
            name: null,// 名称
            industry_id: null,// 行业id
            address: null,// 地址
            funnels: [],// 销售漏斗
            selection_reasons: [],// 选择原因
            budget: null,// 预算
            person_in_charge_id: null,// 负责人id
            group: null,// 所属集团id
            company_launch_background: null,// 客户投放背景
            company_programme: null,//客户方案
            industry_name: null,// 显示文本
            group_name: null,// 显示文本
            person_in_charge_name: null,// 显示文本
        },
        validate: {},
        validateContacts: {},
        validatePutStorage: {},
        beforeClose: (e) => {
            return e === 'cancel'
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        util.showLoading('加载中')
        const that = this
        this.initValidate()
        this.initValidateContacts()
        this.initValidatePutStorage()
        Promise.all([
            this.getDictList('khxg-hy', 'industry_arr', '行业数据初始化失败'),
            this.getDictList('khxg-xzyy', 'selectReasonArr', '选择原因数据初始化失败'),
            this.getDictList('khxg-xsld', 'salesFunnelArr', '销售漏斗数据初始化失败'),
            this.getDictList('khxg-ssjt', 'groupArr', '所属集团数据初始化失败'),
            this.getCompanyArr(),
            this.getUserArr()
        ]).then(() => {
            if (options.id) {
                network.reqPromise('GET', {
                    uri: app.api.customerInfoDetail,
                    params: {id: options.id},
                }).then(res => {
                    that.setData({
                        customer: res.data
                    })
                    console.log(this.data.customer.selection_reasons_name)
                    that.setData({
                        'requestParams.customer_id': options.id
                    })
                    wx.setNavigationBarTitle({
                        title: this.data.customer.name
                    })
                    util.hideLoading()
                }).catch(() => {
                    util.hideLoading()
                })
            }
        }).catch(() => {
            util.hideLoading()
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        if (this.data.active === 4) {
            const component = this.selectComponent('#customerFollowList');
            component.getList()
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    onClose() {
        this.setData({
            show: false
        })
    },
    editInfoDialogClose() {
        this.setData({
            editInfoShow: false,
            editInfo: {
                name: null,// 名称
                industry_id: null,// 行业id
                address: null,// 地址
                funnels: [],// 销售漏斗
                selection_reasons: [],// 选择原因
                budget: null,// 预算
                person_in_charge_id: null,// 负责人id
                group: null,// 所属集团id
                company_launch_background: null,// 客户投放背景
                company_programme: null,//客户方案
                industry_name: null,// 显示文本
                group_name: null,// 显示文本
                person_in_charge_name: null,// 显示文本
            }
        })
    },
    onchange(e) {
        switch (e.detail.index) {
            case 0:
                break;
            case 1:
                this.getContactInfoById()
                break;
            case 3:
                this.getPutStorageById()
                break
            case 4:
                this.selectComponent('#customerFollowList').getList()
                break;
        }
        this.setData({
            active: e.detail.index
        })
    },
    editInfo() {
        let parse = JSON.parse(JSON.stringify(this.data.customer));
        parse.funnels = parse.funnels.map(i => {
            return i.toString()
        })
        parse.selection_reasons = parse.selection_reasons.map(i => {
            return i.toString()
        })
        this.setData({
            editInfoShow: true,
            editInfo: parse
        })
    },
    onLinkUserDialogClose() {
        let obj = {
            name: null,// 名称
            dept: null,// 部门
            post: null,// 职务
            phone: null,// 手机号
            level: null,//等级
            birthday: null,// 生日
            hobbies: null,// 个人喜好
            commemoration_day: null,// 家庭成员及重要纪念日
            remark: null// 备注
        }
        this.setData({
            linkUser: obj,
            addLinkDialogShow: false,
        })
    },
    addLinkUser() {
        this.setData({
            addLinkDialogShow: true
        })
    },
    addPutStore() {
        this.setData({
            addPutStorageShow: true
        })
    },
    addPutStorageClose() {
        let obj = {
            company_head: null,//公司抬头
            login_account: null,//登录账号
            password: null,
            link_user: null,
            phone: null,
            email: null,
            website: null,// 网站
        }
        this.setData({
            putStorage: obj,
            addPutStorageShow: false
        })
    },
    showAddFollowDialog() {
        this.setData({
            show5: true
        })
    },
    // 显示行业弹出层
    showPop(e) {
        let key = e.target.dataset.show
        this.setData({
            [key]: true
        })
    },
    showBirthday(e) {
        let default_time;
        if (!e.target.dataset.default) {
            default_time = new Date().getTime()
        } else {
            default_time = new Date(e.target.dataset.default).getTime();
        }
        this.setData({
            birthdayShow: true,
            index: e.target.dataset.index,
            date: default_time
        });
    },
    onCalendarConfirm(e) {
        this.setData({
            date: formatDate(e.detail),
            calendarShow: false
        });
    },
    onCalendarClose() {
        this.setData({
            calendarShow: false
        });
    },
    getIndustryList() {
        util.showLoading('加载中')
        const that = this
        network.GET({
            uri: app.api.industryList,
            success(res) {
                that.setData({
                    industry_arr: res.data
                })
                util.hideLoading()
            },
            fail() {
                util.hideLoading()
            }
        })
    },
    showCalendar() {
        this.setData({
            calendarShow: true
        });
    },
    preventTouchMove() {

    },
    getContactInfoById() {
        util.showLoading('加载中')
        network.reqPromise('GET', {
            uri: app.api.getContactInfoById,
            params: {id: this.data.customer.id},
        }).then(res => {
            util.hideLoading()
            this.setData({
                contactList: res.data
            })
        }).catch(() => {
            this.setData({
                contactList: []
            })
            util.hideLoading()
        })
    },
    getPutStorageById() {
        util.showLoading('加载中')
        network.reqPromise('GET', {
            uri: app.api.getPutStorageById,
            params: {id: this.data.customer.id},
        }).then(res => {
            util.hideLoading()
            this.setData({
                putStorageList: res.data
            })
        }).catch(() => {
            this.setData({
                putStorageList: []
            })
            util.hideLoading()
        })
    },
    onPopConfirm(e) {
        console.log(e)
        let show = e.target.dataset.show;
        let key = e.target.dataset.key;
        let value_key = e.target.dataset.value;
        let text = e.target.dataset.text
        let textValue = e.target.dataset.textvalue
        if (text) {
            this.setData({
                [text]: e.detail.value[textValue]
            });
        }
        this.setData({
            [key]: value_key ? e.detail.value[value_key] : e.detail.value,
            [show]: false,
        });
    },
    onConfirmBirthday(e) {
        let key = 'linkUser.birthday'
        this.setData({
            [key]: formatDate(new Date(e.detail)),
            birthdayShow: false,
        });
    },
    onCancelPop(e) {
        let key = e.target.dataset.show;
        this.setData({
            [key]: false,
        });
    },
    // 初始化子公司数据
    getCompanyArr() {
        const that = this
        return new Promise((resolve, reject) => {
            network.reqPromise('GET', {
                uri: app.api.companyList
            }).then(res => {
                that.setData({
                    companyArr: res.data
                })
                resolve()
            }).catch(() => {
                Toast.fail({
                    message: '初始化公司数据失败',
                    context: that,
                    selector: '#custom-selector'
                });
                reject()
            })
        })
    },
    // 初始化人员信息
    getUserArr() {
        const that = this
        return new Promise((resolve, reject) => {
            network.reqPromise('GET', {
                uri: app.api.allUserList
            }).then(res => {
                that.setData({
                    userArr: res.data
                })
                resolve()
            }).catch(() => {
                Toast.fail({
                    message: '初始化用户数据失败',
                    context: that,
                    selector: '#custom-selector'
                });
                reject()
            })
        })
    },
    //初始化字典数据
    getDictList(code, data, failMsg) {
        const that = this
        return new Promise((resolve, reject) => {
            network.reqPromise('GET', {
                uri: app.api.getDictData,
                params: {code: code}
            }).then(res => {
                that.setData({
                    [data]: res.data
                })
                resolve()
            }).catch(() => {
                Toast.fail({
                    message: failMsg,
                    context: that,
                    selector: '#custom-selector'
                });
                reject()
            })
        })
    },
    // 验证函数
    initValidate() {
        const rules = {
            name: {
                required: true
            },
            industry_id: {
                required: true
            },
            address: {
                required: true,
            },
            person_in_charge_id: {
                required: true
            },
            group: {
                required: true
            }
        }
        const messages = {
            name: {
                required: '请输入项目名称'
            },
            industry_id: {
                required: '请选择行业'
            },
            address: {
                required: '请输入客户地址',
            },
            person_in_charge_id: {
                required: '请选择客户负责人'
            },
            group: {
                required: '请选择集团'
            },
        }
        this.data.validate = new Validate(rules, messages)
    },
    // 验证函数
    initValidateContacts() {
        const rules = {
            name: {
                required: true
            },
            phone: {
                required: true,
                tel: true
            }
        }
        const messages = {
            name: {
                required: '请输入联系人名称'
            },
            phone: {
                required: '请输入手机号',
                tel: '请输入正确的手机号'
            }
        }
        this.data.validateContacts = new Validate(rules, messages)
    },
    // 验证函数
    initValidatePutStorage() {
        const rules = {
            website: {
                required: true,
                url: true
            },
            company_head: {
                required: true
            },
            login_account: {
                required: true
            },
            password: {
                required: true
            }
        }
        const messages = {
            website: {
                required: '请输入网址',
                url: '请输入正确的网址'
            },
            company_head: {
                required: '请选择公司抬头'
            },
            login_account: {
                required: '请输入登录账号'
            },
            password: {
                required: '请输入登录密码'
            }
        }
        this.data.validatePutStorage = new Validate(rules, messages)
    },
    // 输入框输change
    onInputChange(e) {
        const key = e.target.dataset.key;
        this.setData({
            [key]: e.detail
        })
    },
    linkUserDialogConfirm() {
        if (!this.data.validateContacts.checkForm(this.data.linkUser)) {
            Toast.fail({
                message: this.data.validateContacts.errorList[0].msg,
                context: this,
                selector: '#custom-selector'
            })
        } else {
            let req = Object.assign({}, this.data.linkUser)
            req.customer_id = this.data.customer.id
            const that = this
            util.showLoading('提交中')
            network.reqPromise('POST', {
                uri: app.api.addContract,
                params: req
            }).then(res => {
                Toast.success({
                    message: '操作成功',
                    context: this,
                    selector: '#custom-selector'
                })
                that.onLinkUserDialogClose()
                setTimeout(() => {
                    that.getContactInfoById()
                }, 500)
                util.hideLoading()
            }).catch(() => {
                util.hideLoading()
            })
        }
    },
    addPutStorageConfirm() {
        if (!this.data.validatePutStorage.checkForm(this.data.putStorage)) {
            Toast.fail({
                message: this.data.validatePutStorage.errorList[0].msg,
                context: this,
                selector: '#custom-selector'
            })
        } else {
            let req = Object.assign({}, this.data.putStorage)
            req.customer_id = this.data.customer.id
            const that = this
            util.showLoading('提交中')
            network.reqPromise('POST', {
                uri: app.api.addPutStorage,
                params: req
            }).then(res => {
                Toast.success({
                    message: '操作成功',
                    context: this,
                    selector: '#custom-selector'
                })
                that.addPutStorageClose()
                setTimeout(() => {
                    that.getPutStorageById()
                }, 500)
                util.hideLoading()
            }).catch(() => {
                util.hideLoading()
            })
        }
    },
    editInfoDialogConfirm() {
        if (!this.data.validate.checkForm(this.data.editInfo)) {
            Toast.fail({
                message: this.data.validate.errorList[0].msg,
                context: this,
                selector: '#custom-selector'
            })
        } else {
            if (this.data.editInfo.funnels && this.data.editInfo.funnels.length) {
                const that = this
                const req = that.data.editInfo;
                req.customer_id = req.id
                req.id = null
                util.showLoading('提交中')
                network.reqPromise('POST', {
                    uri: app.api.editSubmit,
                    params: req
                }).then(res => {
                    Toast.success({
                        message: '提交成功',
                        context: this,
                        selector: '#custom-selector'
                    })
                    that.editInfoDialogClose()
                    util.hideLoading()
                }).catch(() => {
                    util.hideLoading()
                })
            } else {
                Toast.fail({
                    message: '销售漏斗最少包含一项',
                    context: this,
                    selector: '#custom-selector'
                })
            }
        }
    },
    // 多选框选择事件
    onCheckBoxChange(e) {
        const key = e.target.dataset.key;
        this.setData({
            [key]: e.detail,
        });
    },
})